import {createStore, combineReducers} from 'redux';
import {connect as reactConnect} from 'react-redux';
import Config from '../Config';

// 全局store
let store: any,
    // BaseReducer子类类名对应详细信息Map
    reducerMap: any;
    // 存储初始化过的所有class
    // initClassList = [],
    // INIT_TYPE = "@abao";

/**
 * 根据Reducer对象为组件注入store state,
 * @param component 组件
 * @param reducerClassTs 要绑定的state 对应的管辖Reducer对象
 */
const connect = (component: any, ...reducerClassTs: Object[]) => {
    return reactConnect(state => {
        let result = {};
        reducerClassTs.forEach(v => {
            // let redObj = v.initState
            // eslint-disable-next-line
            // let obj = new v();
            // let obj = JSON.parse(JSON.stringify(v))
            // console.log(obj.stateFields)

            // 查找reducer类对应管辖的state
            // result[red.stateFields[red.stateFields.length - 1]] = getReducerState(state[Config.storeKey], red);
        });
        return result;
    })(component);
}

/**
 * 根据类对象查找Reducer详细信息
 * @param classT BaseReducer子类
 * @returns {*}
 */
let getReducerObj = (classT: any) => {
    console.log(classT)
    let redObj = reducerMap[classT.initState];
    if(!redObj){
        throw new Error(`${classT.initState}对象不存在,请确认是否在ReducerIndex.js文件中引入`);
    }
    return redObj;
};

/**
 * 查找reducer类对应管辖的state
 * @param state 总的state
 * @param red BaseReducer子类的实例化对象
 * @returns 对应管辖的state
 */
// let getReducerState = (state: any, red: any) => {
//     let targetState = state;
//     // 查找管辖的state
//     red.stateFields.forEach(field => {
//         targetState = targetState[field];
//     });
//     return targetState;
// };

/**
 * 初始化一个Store
 * @returns {Store<any> | *}
 */
const initStore = () => {
    if(store){
        throw new Error("不能多次初始化");
    }
    let reducers = {
        [Config.storeKey]: function(){
            return {}
        }
    }
    store = createStore(combineReducers(reducers));
    // dispatch = store.dispatch;
    return store;
}

initStore()

export { store, initStore, connect }